/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package myftp.app.action;

import java.io.IOException;
import javax.swing.JTabbedPane;
import myftp.core.controller.FrontController;
import myftp.app.form.ConnectForm;
import myftp.app.model.ServerModel;
import myftp.app.model.ServerManagerModel;
import myftp.app.view.ServerTabPartView;
import myftp.app.view.dialog.TemplateDialog;
import myftp.core.Template;
import myftp.core.action.AbstractAction;

/**
 *
 * @author CAVARLE Glenn, LUCAS Stéphane
 * Etablit une nouvelle connexion vers un serveur
 * (dans un nouvel onglet)
 */
public class CreateServerAction extends AbstractAction {

    public synchronized void run() {
        ((ServerManagerModel) this.getModel()).setConnectionAttempt(true);
        ServerModel server = null;
        Template layout = Template.getInstance();
        JTabbedPane tabContainer = (JTabbedPane) layout.getViewPart("tabContainer");
        ServerTabPartView tab = new ServerTabPartView();

        try {
            server = new ServerModel(
                    (String) this.getParam("host"),
                    Integer.parseInt((String) this.getParam("port")));

            server.login((String) this.getParam("login"),
                    (String) this.getParam("password"));
            ((ServerManagerModel) this.getModel()).addServer(server);

            FrontController front;
            front = FrontController.getInstance();
            front.setActionParam("server", server);
            front.dispatch("PromptAction");

            if (server.isLoggedIn()) {
                tab.setModel(server);
                tab.init();
                tabContainer.addTab(null, tab);
                tabContainer.setTabComponentAt(
                        ((ServerManagerModel) this.getModel()).getTabs().indexOf(server.getConnectIndex()),
                        tab.getTabTitle());
            } else {
                try {
                    ((ServerManagerModel) this.getModel()).disconnect(server.getConnectIndex());
                    TemplateDialog.showFailedConnectDialog();
                } catch (InterruptedException ex) {
                }
            }
        } catch (IOException ex) {
            TemplateDialog.showErrorFtpDialog((String) this.getParam("host"));
        }
        ((ServerManagerModel) this.getModel()).setConnectionAttempt(false);


    }

    public boolean init() {
        if (((ServerManagerModel) this.getModel()).hasServers()) {
            Integer response = TemplateDialog.showNewConnectDialog();

            if (response == TemplateDialog.NO_OPTION) {
                return false;
            }
        }

        if (!((ConnectForm) this.getParam("form")).isValid()) {
            return false;
        }
        this.getParams().putAll(((ConnectForm) this.getParam("form")).toMap());
        return true;
    }
}
